﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.WSA;

public class SearchScriptWindow : EditorWindow
{

    [MenuItem("Assets/搜索脚本")]
    static void SearchAssets()
    {
        if (Selection.objects.Length == 0)
            return;
        var value = Selection.objects[0];
        var path = AssetDatabase.GetAssetPath(value);
        if( Path.GetExtension(path) == ".cs")
        {
            var fileName = Path.GetFileName(path).Replace(".cs",string.Empty);

            var window = GetWindow<SearchScriptWindow>("搜索脚本");
            window.search = AssetDatabase.LoadAssetAtPath<MonoScript>(path).GetClass().Name;
            window.Search();
            window.Show();
        }
    }

    int select=-1;
    Vector2 pos;
    public string search;
    UnityEngine.Object[] array;
    private void OnGUI()
    {
        search = EditorGUILayout.TextField("脚本名称", search);
        if(GUILayout.Button("搜索",GUILayout.MinHeight(20)))
        {
            Search();
        }

        pos = EditorGUILayout.BeginScrollView(pos);
        {
            ForArray();
        }
        EditorGUILayout.EndScrollView();
    }

    public void Search()
    {
        if (string.IsNullOrEmpty(search))
        {
            Debug.LogError("脚本为空");
            return;
        }

        
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            var type = assembly.GetType(search);
            if (type == null)
                continue;
            array = Resources.FindObjectsOfTypeAll(type);
            break;
        }
        select = -1;
    }

    void ForArray()
    {
        if (array == null)
            return;

        for(int i=0;i<array.Length;i++)
        {
            var mono = array[i] as MonoBehaviour;
            if (mono == null)
            {
                array = null;
                break;
            }
            var rect = EditorGUILayout.GetControlRect(GUILayout.MinHeight(20));
            if(i == select)
            {
                 EditorGUI.DrawRect(rect,Color.yellow);
            }
            if (GUI.Button(rect,GetTransPath(mono.transform), "Label"))
            {
                select = i;
                Selection.activeObject = mono.gameObject;
            }
        }
    }

    public static string GetTransPath(Transform trans)
    {
        if (!trans.parent)
        {
            return trans.name;
        }
        return GetTransPath(trans.parent) + "/" + trans.name;
    }
}
